<template>
  <div class="user-edit-container">
    <div class="header">
      <button class="back-button" @click="goBack">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#50b1ab" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M19 12H5M12 19l-7-7 7-7"/>
        </svg>
        返回
      </button>
      <h2 class="title">修改个人信息</h2>
    </div>

    <form @submit.prevent="submitForm" class="edit-form">
      <!-- 用户名 -->
      <div class="form-item">
        <label>用户名:</label>
        <input type="text" v-model="form.username" placeholder="请输入用户名" />
      </div>

      <!-- 邮箱 -->
      <div class="form-item">
        <label>邮箱:</label>
        <input type="email" v-model="form.email" placeholder="请输入邮箱" />
      </div>

      <!-- 昵称 -->
      <div class="form-item">
        <label>昵称:</label>
        <input type="text" v-model="form.nickname" placeholder="请输入昵称" />
      </div>

      <!-- 个性签名 -->
      <div class="form-item">
        <label>个性签名:</label>
        <textarea v-model="form.bio" placeholder="请输入个性签名" rows="3"></textarea>
      </div>

      <!-- 密码区域 -->
      <div class="password-section">
        <h3 class="password-title">修改密码（选填）</h3>
        
        <div class="form-item">
          <label>原密码:</label>
          <input type="password" v-model="form.oldPassword" placeholder="请输原密码" />
        </div>
        
        <div class="form-item">
          <label>新密码:</label>
          <input type="password" v-model="form.password" placeholder="请输入新密码（至少6位）" />
          <p class="hint" v-if="form.password && form.password.length < 6">
            密码长度不能少于6位
          </p>
        </div>

        <!-- 确认密码 -->
        <div class="form-item">
          <label>确认新密码:</label>
          <input type="password" v-model="form.passwordConfirm" placeholder="请再次输入新密码" />
          <p class="error-message" v-if="form.password && form.passwordConfirm && form.password !== form.passwordConfirm">
            两次输入的密码不一致
          </p>
        </div>
      </div>

      <!-- 全局错误 -->
      <p class="error" v-if="error">{{ error }}</p>

      <!-- 加载状态 -->
      <div class="loading-overlay" v-if="isSubmitting">
        <div class="spinner"></div>
        <p>保存中...</p>
      </div>

      <!-- 按钮组 -->
      <div class="form-actions">
        <button type="button" class="secondary-button" @click="resetForm" :disabled="isSubmitting">重置</button>
        <button type="submit" class="primary-button" :disabled="!canSubmit || isSubmitting">保存修改</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { ElMessage, ElLoading } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()

// 表单数据
const form = reactive({
  username: '',
  email: '',
  nickname: '',
  bio: '',
  oldPassword: '',
  password: '',
  passwordConfirm: ''
})

// 状态管理
const error = ref('')
const isSubmitting = ref(false)
const originalFormState = ref({})

// 初始化表单数据
onMounted(async () => {
  try {
    // 确保用户数据已加载
    if (!authStore.user) {
      await authStore.fetchCurrentUser()
    }
    
    if (authStore.user) {
      form.username = authStore.user.username ?? ''
      form.email    = authStore.user.email ?? ''
      form.nickname = authStore.user.nickname ?? ''
      form.bio      = authStore.user.bio ?? ''
      
      // 保存原始状态用于重置
      originalFormState.value = { ...form }
    } else {
      error.value = '无法获取用户信息，请重新登录'
      setTimeout(() => router.push('/login'), 2000)
    }
  } catch (err) {
    error.value = err.message || '加载用户信息失败'
    console.error('初始化表单失败:', err)
  }
})

// 表单验证
const canSubmit = computed(() => {
  // 基础信息验证
  if (!form.username || !form.email || !form.nickname) {
    return false
  }
  
  // 邮箱格式简单验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(form.email)) {
    return false
  }
  
  // 密码修改验证
  if (form.password) {
    // 密码长度验证
    if (form.password.length < 6) {
      return false
    }
    // 密码一致性验证
    if (form.password !== form.passwordConfirm) {
      return false
    }
    // 原密码验证
    if (!form.oldPassword) {
      return false
    }
  }
  
  return true
})

// 监听密码变化，清除相关错误
watch(() => form.password, () => {
  if (error.value.includes('密码')) {
    error.value = ''
  }
})

// 返回上一页
const goBack = () => router.back()

// 提交表单
const submitForm = async () => {
  if (!canSubmit.value) {
    error.value = '请检查表单填写是否正确'
    return
  }
  
  error.value = ''
  isSubmitting.value = true
  
  try {
    // 准备提交的数据
    const submitData = {
      userDto: {
        username: form.username,
        email: form.email,
        nickname: form.nickname,
        bio: form.bio
      },
      pwdDto: form.password ? {
        oldPassword: form.oldPassword,
        newPassword: form.password
      } : null
    }
    
    // 调用更新接口
    const res = await authStore.updateProfile(submitData)
    
    // 检查响应是否有效
    if (!res) {
      throw new Error('更新失败，未收到响应')
    }
    
    if (res.success) {
      ElMessage.success('个人信息更新成功')
      // 跳转到个人资料页，并强制刷新数据
      router.replace('/profile').then(() => {
        // 通知个人资料页刷新数据
        window.dispatchEvent(new CustomEvent('profile-updated'))
      })
    } else {
      error.value = res.message || '更新失败，请稍后重试'
      // 处理会话过期情况
      if (res.message?.includes('会话已过期') || res.message?.includes('用户不存在')) {
        ElMessage.error('会话已过期，请重新登录')
        setTimeout(() => router.push('/login'), 1500)
      }
    }
  } catch (err) {
    console.error('提交表单错误:', err)
    error.value = err.message || '更新过程中发生错误'
  } finally {
    isSubmitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  const u = authStore.user || {}
  form.username = u.username ?? ''
  form.email    = u.email ?? ''
  form.nickname = u.nickname ?? ''
  form.bio      = u.bio ?? ''
  form.oldPassword = ''
  form.password = ''
  form.passwordConfirm = ''
  error.value = ''
}
</script>

<style scoped>
.user-edit-container {
  max-width: 600px;
  margin: 2rem auto;
  padding: 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
}

.header {
  position: relative;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eaeaea;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: none;
  border: none;
  color: #50b1ab;
  font-weight: 500;
  cursor: pointer;
  padding: 0.5rem 0;
  transition: all 0.2s ease;
}

.back-button:hover {
  opacity: 0.8;
}

.title {
  text-align: center;
  color: #333;
  font-size: 1.5rem;
  margin-top: 1rem;
}

.edit-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.password-section {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px dashed #eaeaea;
}

.password-title {
  color: #666;
  font-size: 1rem;
  margin-bottom: 1rem;
  font-weight: 500;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

label {
  font-size: 0.9rem;
  color: #555;
  font-weight: 500;
}

input,
textarea {
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.2s ease;
}

input:focus,
textarea:focus {
  border-color: #50b1ab;
  box-shadow: 0 0 0 3px rgba(80, 177, 171, 0.1);
  outline: none;
}

textarea {
  min-height: 100px;
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

.primary-button {
  background-color: #50b1ab;
  color: white;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.primary-button:hover:not(:disabled) {
  background-color: #3f9e99;
  transform: translateY(-1px);
}

.primary-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  opacity: 0.7;
}

.secondary-button {
  background-color: white;
  color: #50b1ab;
  padding: 0.75rem 1.5rem;
  border: 1px solid #50b1ab;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.secondary-button:hover:not(:disabled) {
  background-color: rgba(80, 177, 171, 0.05);
}

.secondary-button:disabled {
  color: #999;
  border-color: #ddd;
  cursor: not-allowed;
}

.error {
  color: #ff4d4f;
  font-size: 0.85rem;
  margin-top: 0.25rem;
  padding: 0.5rem;
  background-color: rgba(255, 77, 79, 0.05);
  border-radius: 4px;
}

.error-message {
  color: #ff4d4f;
  font-size: 0.85rem;
  margin-top: 0.25rem;
}

.hint {
  color: #666;
  font-size: 0.85rem;
  margin-top: 0.25rem;
  color: #888;
}

/* 加载状态样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  gap: 1rem;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(80, 177, 171, 0.2);
  border-radius: 50%;
  border-top-color: #50b1ab;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 响应式调整 */
@media (max-width: 640px) {
  .user-edit-container {
    padding: 1.5rem;
    margin: 1rem;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .primary-button,
  .secondary-button {
    width: 100%;
  }
}
</style>
